package com.isa.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.security.PublicKey;

import javax.crypto.SecretKey;
import javax.enterprise.inject.New;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.omg.CORBA.PUBLIC_MEMBER;

import com.isa.crypto.CryController;
import com.isa.crypto.Crypto;
import com.isa.util.Arguments;
import com.sun.mail.iap.Argument;
import com.sun.mail.iap.ByteArray;

public class KeyChanger extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public KeyChanger() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.service(req, resp);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		if (request.getParameter("action").equals("getpubkey")) {
			ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
			System.out.println(request.getParameter("keytype"));
			KeyPair keyPair = Crypto.generateKeyPair(request
					.getParameter("keytype"));
			PublicKey puk = keyPair.getPublic();
			Arguments.prk = keyPair.getPrivate();
//			out.write("hahahahah");
//			System.err.println("hahahahah".getBytes());
			
			System.out.println(puk.getEncoded().length);
			System.out.println(puk.getEncoded());
			oos.writeObject(puk);
			oos.flush();
			oos.close();

		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		ServletInputStream is = request.getInputStream();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			CryController.copyStream(is, baos);
		} catch (Exception e) {
			e.printStackTrace();
		}
		byte[] keybytes = baos.toByteArray();
		System.out.println(keybytes);
		Arguments.sKey = (SecretKey) CryController.unwrapKey(keybytes,
				Arguments.prk);

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
